package cacco.jp.mld.panel.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cacco.jp.mld.panel.entity.UserEntity;
import cacco.jp.mld.panel.sercurity.Role;
import cacco.jp.mld.panel.sercurity.UserDetail;
import cacco.jp.mld.panel.service.UserService;

@Repository
public class UserDetailDao {
	 
	@Autowired
	private UserService userService;
	
	public UserDetail loadUserByUsername(final String username) {
		UserDetail user = new UserDetail();
		UserEntity  entity  = searchDatabase(username);
		if(entity != null){
			user.setUsername(entity.getUserName());
			user.setPassword(entity.getPassword());
			Role r = new Role();
	        r.setName("ROLE_USER");
	        List<Role> roles = new ArrayList<Role>();
	        roles.add(r);
	        user.setAuthorities(roles);
	        return user;
		}
		throw new RuntimeException("User does not exist!");
    }
	public UserEntity searchDatabase(String username) {
		  // Retrieve all users from the database
		  List<UserEntity> users = internalDatabase();
		  // Search user based on the parameters
		  for(UserEntity dbUser:users) {
		   if ( dbUser.getUserName().equals(username)  == true ) {
		    // return matching user
		    return dbUser;
	        }
		  }
		  throw new RuntimeException("User does not exist!");
	}
	private List<UserEntity> internalDatabase() {
		  // Dummy database
		   
		  // Create a dummy array list
		  List<UserEntity> users = userService.getAll();
		  for(UserEntity user: users){
			  
		  }
		  return users;
		 }
}
